package com.example.ross.security;

import com.alibaba.fastjson.JSON;
import com.example.ross.common.Result;
import com.example.ross.utils.JwtUtil;
import com.example.ross.utils.RedisUtil;
import com.example.ross.utils.WebUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0.0
 * @className: RossLogoutSuccessHandler
 * @description: 自定义退出处理类 返回成功
 * @author: zhangjunfa
 * @date: 2023/5/7 11:22
 */
@Slf4j
@Component
public class RossLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserIdByJwt(token);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        log.info("注销用户：{}", userId);
        redisUtil.delete("login:" + userId);
        String json = JSON.toJSONString(Result.success());
        WebUtil.renderString(response, json);
    }

}
